package com.gateway.plugin.resilience4j.executor;

import com.gateway.plugin.resilience4j.config.Resilience4JConfig;
import com.gateway.plugin.resilience4j.factory.Resilience4JRegistryFactory;
import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.reactor.ratelimiter.operator.RateLimiterOperator;
import reactor.core.publisher.Mono;

import java.util.Optional;
import java.util.function.Function;

/**
 * @program: api-gateway
 * @description: Rate limiter executor.
 * @author: YuKai Fan
 * @create: 2025/2/24 10:15
 **/
public class RateLimiterExecutor implements Executor {

    @Override
    public <T> Mono<T> run(Mono<T> toRun, Function<Throwable, Mono<T>> fallback, Resilience4JConfig conf) {
        RateLimiter rateLimiter = Resilience4JRegistryFactory.rateLimiter(conf.getId(), conf.getRateLimiterConfig());
        Mono<T> to = toRun.transformDeferred(RateLimiterOperator.of(rateLimiter));
        return Optional.ofNullable(fallback)
                .map(to::onErrorResume)
                .orElse(to);
    }
}
